package com.nzw.controller.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nzw.common.Constant;
import com.nzw.common.service.wx.WXPlatform;
import com.nzw.controller.common.AbstractController;
import com.nzw.redis.impl.common.RedisTemplate;
import com.nzw.security.token.UserToken;
import com.nzw.service.member.MemberService;
import com.nzw.service.wx.WXService;
import com.nzw.utils.ServletUtil;
import com.nzw.vo.common.HttpResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by ywx on 2018/1/24.
 */
@RequestMapping("/wx")
@Controller
public class WXController extends AbstractController {
    @Autowired
    WXPlatform wxPlatform;
    @Autowired
    WXService wxService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    MemberService memberService;
    @Autowired
    HttpSession httpSession;





    @GetMapping("/getTicket")
    @ResponseBody
    public HttpResult getSignature(){

        return new HttpResult(HttpResult.OK,wxService.getJsticket());
    }




    //获取微信js
    @GetMapping("/getJsApi")
    @ResponseBody
    public HttpResult getSignature(@RequestParam String url,
                                   @RequestParam Boolean refresh){

        return new HttpResult(HttpResult.OK,wxService.getJsApi(url,refresh));
    }




    /**2
     * 重定向到用户授权页
     *
     * @return
     */
    @RequestMapping("userAuthorize")
    public String userAuthorize(@RequestParam String state, Model model) {
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize";
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("appid", wxPlatform.getPublicAppid());
        params.put("redirect_uri", URLEncoder.encode(Constant.USER_AUTH_CALL_BACK));
        params.put("response_type", "code");
        params.put("scope", "snsapi_userinfo");
        if (state.contains(","))
            state = state.split(",")[0];
        params.put("state", state);
        model.addAttribute("url", ServletUtil.generateUrlFixByMap(url, params) + "#wechat_redirect");
        return "com/auth/userAuth";
    }





    /**
     * 用户授权的回调
     *
     * @param code  授权code
     * @param state 自定义信息
     */
    @RequestMapping("/userAuthCallBack")
    public String userAuthCallBack(@RequestParam String code, @RequestParam String state) {
        String entity = wxService.getWebAccessToken(code);
        JSONObject jsonObject = JSON.parseObject(entity);
        String openId = jsonObject.getString("openid");
        Subject subject = SecurityUtils.getSubject();
        String json = redisTemplate.get("state:" + state);
        JSONObject stateJson = JSON.parseObject(json);

        System.out.println("微信返回:" + stateJson);
        if (!subject.isAuthenticated()) {
            String recomemderOpenId=null;
            if (stateJson.containsKey("oid"))
                recomemderOpenId=stateJson.getString("oid");//推荐人openId
            wxService.saveWXUserInfo(recomemderOpenId, openId, jsonObject.getString("access_token"));//保存用户基本信息
            /**
             * 登录
             */
            UserToken userToken = new UserToken(openId, openId, Constant.WX_LOGIN, false, null, ServletUtil.getHost());
            subject.login(userToken);
            System.out.println("登录成功:" + subject.getSession().getId());
          //  memberService.saveLoginRecord(openId);保存登录记录
        }

        redisTemplate.del("state:" + state);
        System.out.println("重定向的url："+stateJson.getString("url"));

        //重定向到用户点击的页面
        return "redirect:" + stateJson.getString("url");
    }
}
